﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.Utils;
using NP.BPMReportPlatform.ZHLC.Dto;
using SqlSugar;
using Volo.Abp.Application.Dtos;

namespace NP.BPMReportPlatform.ZHLC
{
    public class ZHLCService : BPMReportPlatformAppService, IZHLCService
    {
        private readonly SqlSugarClient _db;
        private readonly SqlSugarClient _dbPlatform;
        private readonly IBPMUtilsAppService _bPMUtilsApp;
        private readonly IBPMPlatformAppService _iBPMPlatformApp;

        public ZHLCService(ISqlSugarAppService sqlSugarAppService, IBPMUtilsAppService bPMUtilsApp
            , IBPMPlatformAppService iBPMPlatformApp)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _bPMUtilsApp = bPMUtilsApp;
            _iBPMPlatformApp = iBPMPlatformApp;
        }

        public async Task<PagedResultDto<GetZHLCOutput>> GetAllAsync(GetZHLCInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x => x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId));

            //返回结果
            return new PagedResultDto<GetZHLCOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        public async Task<List<GetZHLCOutput>> ExportAsync(GetZHLCInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            return listViewDto;
        }


        private ISugarQueryable<GetZHLCOutput> GetQueryable(GetZHLCInput input)
        {
            var currentUserId = Guid.Empty;
            if (!input.IsQueryAll)
            {
                var currentUserDto = _dbPlatform.Queryable<Users>().Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First();
                if (currentUserDto != null)
                {
                    currentUserId = currentUserDto.UserId;
                }
            }
            var listQueryable = _db.Queryable<ZHLCHeader, BusinessProcessesNew>(
                    (x, b) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == b.InstanceId)
                )
                .WhereIF(!input.IsQueryAll, x => x.AddUserId.Equals(currentUserId))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber),x => x.InstanceNumber == input.InstanceNumber)
                .WhereIF(!string.IsNullOrWhiteSpace(input.OrderStatus) && input.OrderStatus == "已审批", (x, b) => b.IsEnd == true)
                .WhereIF(!string.IsNullOrWhiteSpace(input.OrderStatus) && input.OrderStatus == "待审批", (x, b) => b.IsEnd == null)
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Contains(input.AddUserName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Area), x => x.Area.Contains(input.Area))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Classification),x => x.Classification == input.Classification)
                .WhereIF(!string.IsNullOrWhiteSpace(input.RecallScope),x => x.RecallScope == input.RecallScope)
                .WhereIF(!string.IsNullOrWhiteSpace(input.EstimatedLoss),x => x.EstimatedLoss == input.EstimatedLoss)
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                    x => x.AddTime >= input.StartCreationTime && x.AddTime <= input.EndCreationTime)
                .Select((x, b) => new GetZHLCOutput()
                {
                    InstanceNumber = x.InstanceNumber,
                    ProcessStartTime = x.AddTime,
                    ProcessStartUserName = x.AddUserName,
                    OrderStatus = b.IsEnd ==true?"已审批":"待审批",
                    Title=x.Title,
                    Content=x.Content,
                    Content1=x.Content1,
                    Content2=x.Content2,
                    Area = x.Area,
                    Classification =x.Classification,
                    RecallScope = x.RecallScope,
                    EstimatedLoss =x.EstimatedLoss,
                    TransportNumber =x.TransportNumber,
                    Remark=x.Remark
                }).MergeTable().Distinct().OrderBy(ins => ins.ProcessStartTime, OrderByType.Desc);
            return listQueryable;
        }
    }
}